package club.itstudio.itouc.controller.jw.stu

import club.itstudio.itouc.config.ElectiveCoursecConfig
import club.itstudio.itouc.config.LessonConfig
import club.itstudio.itouc.core.exception.ITOUCException
import club.itstudio.itouc.core.util.Result
import club.itstudio.itouc.core.util.ResultUtil
import club.itstudio.itouc.jw.ParamsBuilder
import club.itstudio.itouc.jw.with
import club.itstudio.itouc.service.JwOps
import club.itstudio.itouc.util.Redis
import org.springframework.web.bind.annotation.CookieValue
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/jw/stu/timetable")
class TimeTable (val jwOps: JwOps,
                 val jw: ParamsBuilder,
                 val redis: Redis,
                 val lessonConfig: LessonConfig,
                 val ecConfig: ElectiveCoursecConfig){
    /**
     * 获取选课列表
     */
    @GetMapping
    fun timeTable(@CookieValue token: String): Result<Any> {
        val session = jwOps.getValidJwSession(token)
        // 获取用户列表，无选课人数数据
        val year = ecConfig.year
        val semester = ecConfig.semester
        val stuCourseList = jwOps.getStuCourseList(session, year, semester).also {
            redis.saveStuCourse(it, session.userCode, year, semester)
        }
        val classNumList = List(stuCourseList.size) {
            stuCourseList[it].classNum
        }
        val courseList = redis.getCourseList(classNumList)
        val data = mapOf(
                "stuCourseList" to stuCourseList,
                "courseList" to courseList
        )
        return ResultUtil.success(data)
    }

    /**
     * 获取二维的课程表，html形式
     */
    @GetMapping("/html")
    fun htmlTimeTable(@CookieValue token: String): Result<Any> {
        val session = jwOps.getValidJwSession(token)
        val data = jw.htmlTimeTable(session.userCode) with session
        return ResultUtil.success(data = data)
    }

    // 获取用户的课程列表，有选课人数
    @GetMapping("/course")
    fun getTimeTable(@CookieValue token: String): Result<Any> {
        val stuCourseList = jwOps.getCacheStuCourseList(token, lessonConfig.year, lessonConfig.semester)
        return ResultUtil.success(stuCourseList)
    }
}